package com.xhs.minio.controller;

import com.xhs.minio.core.message.ReturnResult;
import com.xhs.minio.core.utils.MinIoUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desc: minio 的控制器
 * @projectName: spring-boot-minio
 * @author: xhs
 * @date: 2025-08-17 周日 12:35
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/minio")
public class MinioController {

    @Resource
    private MinIoUtil minIoUtil;

    /**
     * 校验存储桶是否存在
     *
     * @param bucketName 桶名称
     * @return ReturnResult<String>
     */
    @GetMapping("/isBucketName")
    public ReturnResult<Object> isBucketName(@NotEmpty(message = "bucketName不能为空") String bucketName) {
        boolean exist = minIoUtil.doesBucketExist(bucketName);
        if (exist) {
            return ReturnResult.success(true);
        }
        return ReturnResult.error("存储桶不存在", bucketName);
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 桶名称
     * @return ReturnResult<String>
     */
    @GetMapping("/createBucketName")
    public ReturnResult<String> createBucketName(@NotEmpty(message = "bucketName不能为空") String bucketName) {
        boolean exist = minIoUtil.doesBucketExist(bucketName);
        if (exist) {
            return ReturnResult.error("桶已存在", bucketName);
        }
        minIoUtil.makeBucket(bucketName);
        return ReturnResult.success("创建成功", bucketName);
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 桶名称
     * @return ReturnResult<String>
     */
    @GetMapping("/deleteBucketName")
    public ReturnResult<String> deleteBucketName(@NotEmpty(message = "bucketName不能为空") String bucketName) {
        boolean exist = minIoUtil.doesBucketExist(bucketName);
        if (exist) {
            boolean removed = minIoUtil.removeBucket(bucketName);
            if (removed) {
                return ReturnResult.success("删除成功", bucketName);
            }
            return ReturnResult.error("删除失败", bucketName);
        }
        return ReturnResult.error("存储桶不存在", bucketName);
    }
}
